//
//  RHHiSolarkVPPSetVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/7/3.
//

#import "RHHiSolarkVPPSetVC.h"
#import "SYChartTool.h"
#import "ZYSwitch.h"
#import "KWTMGRNSettingSyncVC.h"
#import "SettingOptionController.h"
#import "RHDeviceModel.h"
#import "RHEndPointModel.h"
#import "PasswordVerifyController.h"
#import "RHTools.h"

#import "RHHiSolarSettingChgTimeCell.h"
#import "KWTHiSolarSettingEditTimeVC.h"
#import "WSDatePickerView.h"
#import "NetworkAgent.h"
#import "RHVppSetCommonModel.h"
#import "KWTPlantGroupModel.h"
#import "RHUserGroupModel.h"
#import "JCDataConvert.h"

@interface RHHiSolarkVPPSetVC()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate>
@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *dataArr;

@property (nonatomic ,strong) NSMutableArray *paraSectionArr;//每组的参数

@end
@implementation RHHiSolarkVPPSetVC
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"充放电配置".rh_localized;
    self.paraSectionArr = [NSMutableArray array];
    [self setupUI];
    [self loadParamData];
}

- (void)setupUI{
    kWeakSelf;
    NSArray *arr = [SYChartTool loadJsonFileWithName:@"setting_ao_HiSolar_chg"];
    self.dataArr = [NSArray yy_modelArrayWithClass:[RHVppSetCommonModel class] json:arr];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:kCOLOR_HEX(@"#F0F5FF")];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setSeparatorColor:UIColor.clearColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];

    [_tableView registerClass:[RHHiSolarSettingChgTimeCell class] forCellReuseIdentifier:@"RHHiSolarSettingChgTimeCell"];
    _tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 8)];
    _tableView.tableFooterView = [self footerView];
    [self.view addSubview:_tableView];
     
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.bottom.mas_offset(0);
        make.top.mas_offset(0);
    }];
    
    self.tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    
   
    
}


#pragma mark ------ 1.加载配置参数
-(void)loadParamData
{
    NSDictionary *dic = [self.groupModel.strategy jsonStringToDictionary];
    if (self.userGroupModel) {
        dic = [self.userGroupModel.strategy jsonStringToDictionary];
    }
    NSMutableDictionary *mtbDic = [NSMutableDictionary dictionary];
    NSArray *dicArr = dic[@"commandParamList"];
    [dicArr enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull paraDic, NSUInteger idx, BOOL * _Nonnull stop) {
        [mtbDic setObject:ValidNullData(paraDic[@"value"]) forKey:ValidNullData(paraDic[@"paramName"])];
    }];
    [self readDefult:mtbDic];
}

//读取默认值
- (void)readDefult:(NSDictionary *)dic{
    [self.dataArr enumerateObjectsUsingBlock:^(RHVppSetCommonModel*  _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
       
        [model readHiSolarDefult:dic];
        [model.rows enumerateObjectsUsingBlock:^(RHVppSetCommonModel * _Nonnull rowModel, NSUInteger idx, BOOL * _Nonnull stop_row) {
            //现在设备上传的北京时间,要转成本地时间显示
            if ([rowModel.type isEqualToString:@"date"]) {
                if (rowModel.content.length>6) {
                    rowModel.content = [NSDate beiJinTimeConvertToLocalTime:rowModel.content];
                    *stop_row = YES;
                }
            }
        }];
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0||section == 1) {
        return 20;
    }
    
    return 60;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0||section == 1) {
        UIView *headV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 20)];
        headV.backgroundColor = kCOLOR_HEX(@"#F0F5FF");
        UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 10, kUI_WINDOW_W-30, 10)];
        bgView.backgroundColor = UIColor.whiteColor;
        bgView.layer.cornerRadius = 8;
        bgView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
        bgView.layer.masksToBounds = YES;
        [headV addSubview:bgView];
        return headV;
    }
    
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 60)];
    headerView.backgroundColor = kCOLOR_HEX(@"#F0F5FF");
    RHVppSetCommonModel *sectionModel = self.dataArr[section];
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 15, kUI_WINDOW_W-30, 45)];
    bgView.backgroundColor = UIColor.whiteColor;
    bgView.layer.cornerRadius = 8;
    bgView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    bgView.layer.masksToBounds = YES;
    [headerView addSubview:bgView];
    
    QMUILabel *titleLab = [QMUILabel labelWithText:sectionModel.sectionTitle.rh_localized font:kSYSTEMFONT(16) textColor:kCOLOR_HEX(@"#171A1D")];
    [bgView addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.centerY.mas_offset(0);
    }];
    
    
    UIView *line = kView;
    line.backgroundColor = kCOLOR_HEX_A(@"#7E868E",0.2);
    [bgView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.offset(1);
    }];
    
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 10;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    kWeakSelf;
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 10)];
    footerView.backgroundColor = kCOLOR_HEX(@"#F0F5FF");
//    RHVppSetCommonModel *sectionModel = self.dataArr[section];
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 0, kUI_WINDOW_W-30, 10)];
    bgView.backgroundColor = UIColor.whiteColor;
    bgView.layer.cornerRadius = 8;
    bgView.layer.maskedCorners = kCALayerMinXMaxYCorner|kCALayerMaxXMaxYCorner;
    bgView.layer.masksToBounds = YES;
    [footerView addSubview:bgView];
    
    
    return footerView;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    RHVppSetCommonModel *sectionModel = self.dataArr[section];
    return sectionModel.rows.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RHVppSetCommonModel *sectionModel = self.dataArr[indexPath.section];
    RHVppSetCommonModel *rowModel = sectionModel.rows[indexPath.row];
    if ([rowModel.type isEqualToString:@"time"]) {//充放电时段设置
        RHHiSolarSettingChgTimeCell *settingCell = [tableView dequeueReusableCellWithIdentifier:@"RHHiSolarSettingChgTimeCell"];
        rowModel.rowTitle = [NSString stringWithFormat:@"%@ %ld",@"时段".rh_localized,indexPath.row+1];
        settingCell.model = rowModel;
        kWeakSelf;
        settingCell.selectAction = ^(RHVppSetCommonModel * _Nonnull model) {
            [weakSelf editChargeDischargeInfo:model index:indexPath.row+1];
        };
        settingCell.commitAction = ^(RHVppSetCommonModel * _Nonnull model) {
            [weakSelf checkParaEnableStatus];
        };
        settingCell.readAction = ^(RHVppSetCommonModel * _Nonnull model) {
//            [weakSelf readParamData];
        };
        settingCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return settingCell;
    }
    return [UITableViewCell new];
}

#pragma mark -------- 充放电时间段选择
-(void)editChargeDischargeInfo:(RHVppSetCommonModel*)model index:(NSInteger)index
{
    kWeakSelf;
    NSString *type = self.groupModel.type;
    if (self.userGroupModel) {
        type = self.userGroupModel.type;
    }
    KWTHiSolarSettingEditTimeVC *editVC = [[KWTHiSolarSettingEditTimeVC alloc]init];
    editVC.index = index;
    editVC.model = model;
    editVC.sureBlock = ^{
        //编辑了开始时间,上一组的结束时间要跟着变; 编辑了结束时间,下一组的开始时间要跟着变
        [weakSelf.dataArr enumerateObjectsUsingBlock:^(RHVppSetCommonModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
            [sectionModel.rows enumerateObjectsUsingBlock:^(RHVppSetCommonModel * _Nonnull rowModel, NSUInteger idx, BOOL * _Nonnull stop) {
                [rowModel.items enumerateObjectsUsingBlock:^(RHVppSetCommonModel * _Nonnull itemModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    [model.items enumerateObjectsUsingBlock:^(RHVppSetCommonModel * _Nonnull editModel, NSUInteger idx, BOOL * _Nonnull stop) {
                        if ([itemModel.key isEqualToString:editModel.key]) {
                            itemModel.content = editModel.content;
                        }
                    }];
                    
                }];
            }];
        }];
        [weakSelf.tableView reloadData];
    };
    [self.navigationController pushViewController:editVC animated:YES];
}

#pragma mark -------- 选择时间
- (void)dateAction:(RHVppSetCommonModel *)settingModel  {
    
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDayHourMinuteSecond CompleteBlock:^(NSDate *selectDate) {
        NSString *dateFormatStr = @"yyyy/MM/dd HH:mm:ss";
        NSString *currentDate = [selectDate stringWithFormat: dateFormatStr];
        settingModel.content = currentDate;
        [self.tableView reloadData];
    }];
    datePickerV.dateLabelColor = FontColor(@"#3ECE80");//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    [datePickerV show];
}

#pragma mark ------ 选择
-(void)selectAction:(RHVppSetCommonModel*)model
{
    kWeakSelf;
    SettingOptionController *vc = [[SettingOptionController alloc] initWithData:model.selectList];
    [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
    
    vc.curTextValue = [model.content integerValue];
   
    vc.selectBlock = ^(NSInteger index) {
        DevSettingOptionModel *select_model = model.selectList[index];
        model.enumText = select_model.text;//存要显示的内容
        model.content = [NSString stringWithFormat:@"%ld",select_model.textValue];//存下标
        [weakSelf.tableView reloadData];
    };
}


#pragma mark -------- 提交参数前 判断相关使能是否打开
-(void)checkParaEnableStatus
{
    //工作模式没有禁用,电网充电使能,TOU时间使能要打,时间设置才能生效
//    if (self.paraSetValid==NO) {
//        kWeakSelf;
//        QMUIAlertController *alertVC = [[QMUIAlertController alloc]initWithTitle:@"高级工作模式要启用,电网充电使能和TOU时间控制使能要打开,时间设置才能生效!".rh_localized message:nil preferredStyle:QMUIAlertControllerStyleAlert];
//        QMUIAlertAction *sure = [QMUIAlertAction actionWithTitle:@"确定".rh_localized style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
//            [weakSelf commitAction];
//        }];
//        [alertVC addAction:sure];
//        [alertVC showWithAnimated:YES];
//    }else{
        [self commitAction];
//    }
}

#pragma mark -------- 提交参数前 密码校验
-(void)commitAction
{
   
//    if (Password_Check) {
//        PasswordVerifyController *vc = [[PasswordVerifyController alloc] init];
//        [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
//        
//        kWeakSelf;
//        vc.callBackBlock = ^(NSString * _Nonnull password) {
//                    NSDictionary *dic = [RHTools getAccountInfo];
//                    if ([SafeStr(dic[@"password"]) isEqualToString:password]) {
//                        BOOL result = [weakSelf createSectionSetPara];
//                        if (result == NO) return;//校验不过
//                       
//                        [weakSelf devParamsSetFromNetwork];
//                    }else{
//                        [QMUITips showInfo:@"密码错误".rh_localized];
//                    }
//        };
//    }else{
        BOOL result = [self createSectionSetPara];
        if (result == NO) return;//校验不过
      
        [self devParamsSetFromNetwork];
//    }
    
    
}

//把设置指令分组下发   没有值的参数不下发
-(BOOL)createSectionSetPara
{
   
    [self.paraSectionArr removeAllObjects];
   
    //工作模式 0:自发自用 1:备电模式 2:PV全额上网模式 3:PV+Bat全额上网模式 4:VPP模式 5:TOU模式
    NSDictionary *modeDic = @{
        @"paramName": @"Inv5_Mode",
        @"regAddr" : @(4203),
        @"offset" : @(0),
        @"num" : @(16),
        @"dataType" : @"int",
        @"value" : @"4"

    };
    [self.paraSectionArr addObject:modeDic];
    
    __block BOOL isCheckOK = YES;//校验是否通过
    //充电使能和放电使能的值,要将使能值组合成一个参数下发
    NSMutableString *enableValue = [NSMutableString string];
    
    [self.dataArr enumerateObjectsUsingBlock:^(RHVppSetCommonModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
        
        //上一时间段的结束时间,如果有就比较(当前时间段的开始时间要大于上一段的结束时间)
        __block NSString* lastEndTime;
        __block NSInteger lastEndTimeIndex = 0;
        [sectionModel.rows enumerateObjectsUsingBlock:^(RHVppSetCommonModel * _Nonnull rowModel, NSUInteger rowIdx, BOOL * _Nonnull stop_row) {
       
            //时间段设置
            if ([rowModel.type isEqualToString:@"time"]) {

                __block NSString *startTime;//每段的开始时间
                __block NSString *endTime;  //每段的结束时间
                [rowModel.items enumerateObjectsUsingBlock:^(RHVppSetCommonModel * _Nonnull itemModel, NSUInteger idx, BOOL * _Nonnull stop_item) {
                    
                    NSMutableDictionary *itemDic = [NSMutableDictionary dictionary];
                    [itemDic setObject:itemModel.format forKey:@"dataType"];
                    [itemDic setObject:itemModel.key forKey:@"paramName"];
                    [itemDic setObject:ValidNullData(itemModel.content) forKey:@"value"];
                    [itemDic setObject:@(itemModel.regAddr) forKey:@"regAddr"];
                    [itemDic setObject:@(itemModel.num) forKey:@"num"];
                    [itemDic setObject:@(itemModel.offset) forKey:@"offset"];
                    //soc 功率最大值最小值处理
                    if ([itemModel.type isEqualToString:@"number"]) {
                        NSInteger contentValue = [itemModel.content integerValue];
                        if (itemModel.ratio) {
                            NSDecimalNumber *A = [NSDecimalNumber decimalNumberWithString:ValidNullDataToString(itemModel.content, @"0")];
                            NSDecimalNumber *B = [NSDecimalNumber decimalNumberWithString:itemModel.ratio];
                            NSDecimalNumber *result = [A decimalNumberByMultiplyingBy:B];
                            contentValue = [result integerValue];
                        }
                        if(itemModel.minValue){
                            if(contentValue<[itemModel.minValue integerValue]){//开关打开的情况才判断
                                if([itemModel.key containsString:@"Inv5_VS"]){
                                    [QMUITips showInfo:[NSString stringWithFormat:@"时段%ld SOC不能小于%@",rowIdx+1,itemModel.minValue]];
                                }else{
                                    [QMUITips showInfo:[NSString stringWithFormat:@"时段%ld 电流不能小于%@",rowIdx+1,itemModel.minValue]];
                                }
                                isCheckOK = NO;
                                *stop_row = YES;
                                *stop_item = YES;
                                return;
                            }
                           
                        }
                        if (itemModel.maxValue) {
                            if(contentValue>[itemModel.maxValue integerValue]){
                                if([itemModel.key containsString:@"Inv5_VP"]){
                                    [QMUITips showInfo:[NSString stringWithFormat:@"时段%ld SOC不能大于%@",rowIdx+1,itemModel.maxValue]];
                                }else{
                                    [QMUITips showInfo:[NSString stringWithFormat:@"时段%ld 电流不能大于%@",rowIdx+1,itemModel.maxValue]];
                                }
                                isCheckOK = NO;
                                *stop_row = YES;
                                *stop_item = YES;
                                return;
                            }
                        }
                    }
                    
                    //时间  去掉@":"  01:30 --> 0130
                    if ([itemModel.type isEqualToString:@"date"]) {
                        NSString *content = [itemModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                        [itemDic setObject:ValidNullData(content) forKey:@"value"];
                    }
                  
                    //待机 设置成1  不支持待机
                    NSString *chgKey = [NSString stringWithFormat:@"Inv5_VM%ld",rowIdx+1];
                    if ([itemModel.key isEqualToString:chgKey]) {
                        //组合所有使能使能
                        [enableValue insertString:itemModel.content atIndex:0];
                        return;
                    }
                    
                    [self.paraSectionArr addObject:itemDic];
                
                    //判断结束时间是否大于开始时间
                    NSString *startTime_key = [NSString stringWithFormat:@"Inv5_VTS%ld",rowIdx+1];
                    NSString *endTime_key   = [NSString stringWithFormat:@"Inv5_VTE%ld",rowIdx+1];
                  
                    if ([itemModel.key isEqualToString:startTime_key]&&itemModel.content.length>0) {
                        //开始时间
                        startTime = [itemModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                        RHVppSetCommonModel  *endTimeModel = [rowModel.items safeObjectAtIndex:idx+1];
                        if ([endTimeModel.key isEqualToString:endTime_key]&&endTimeModel.content.length>0) {
                            //结束时间
                            endTime = [endTimeModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                        }
                        
                        //判断当前开始时间是否大于上一段结束时间 如果两个是00:00的话不判断
                        BOOL bothZero = ([startTime integerValue]==0)&&([endTime integerValue]==0);
                        if (startTime.length>0 && lastEndTime.length>0) {
                            if (([startTime integerValue]<[lastEndTime integerValue])&&(!bothZero)) {
                                [QMUITips showInfo:[NSString stringWithFormat:@"时段%ld开始时间必须大于或等于时段%ld结束时间".rh_localized,rowIdx+1,lastEndTimeIndex+1]];
                                isCheckOK = NO;
                                return;
                            }
                        }
                    }
                    if ([itemModel.key isEqualToString:endTime_key]&&itemModel.content.length>0) {
                        endTime = [itemModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                        //上一段时间是00:00 - 00:00的话不比较
                        if ([endTime integerValue] != 0) {
                            lastEndTime = endTime;//保存上一时间段的结束时间(有时的情况下)
                            lastEndTimeIndex = rowIdx;
                        }
                    }
                }];
             
                
                if (startTime || endTime) {//如果一组里有一个时间填了,就比较,都没填的话不比较
                    if (([endTime integerValue] <= [startTime integerValue])&&([startTime integerValue]!=0)) {//两个都是00:00的就不比较
                        
                            isCheckOK = NO;
                            [QMUITips showInfo:[NSString stringWithFormat:@"时段%ld结束时间必须大于开始时间".rh_localized,rowIdx+1]];
                        
                    }
                    
                }
            }
            
        }];
        
        
       
        
    }];
    
    //如果没有填写时间段参数
    if(self.paraSectionArr.count<=1){
        isCheckOK = NO;
    }
    
    //校验不通过不提交
    if (isCheckOK == NO) {
        return NO;
    }
    
    NSInteger decimalValue = [JCDataConvert ConvertBinaryStringToDecimal:enableValue];
    NSString *value = [NSString stringWithFormat:@"%ld",decimalValue];
    NSDictionary *enableDic = @{
        @"dataType":@"int",
        @"paramName":@"Inv5_VM",
        @"value":value,
        @"regAddr":@(7224),
        @"num":@(16),
        @"offset":@(0),
    };
    [self.paraSectionArr addObject:enableDic];
    //---------一次性下发------
    //要按寄存器从小到大排列下发
    [self.paraSectionArr sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        if (obj1[@"regAddr"]&&obj2[@"regAddr"]) {
            if ([obj1[@"regAddr"] integerValue] < [obj2[@"regAddr"] integerValue]) {
                return NSOrderedAscending;
            }else if ([obj1[@"regAddr"] integerValue] > [obj2[@"regAddr"] integerValue]){
                return NSOrderedDescending;
            }else{
                return NSOrderedSame;
            }
            
        }else{
            return NSOrderedSame;
        }
    }];
    
    return YES;
}

//把设置指令分组下发   没有值的参数传0
-(void)createSectionReadPara
{
   
    [self.paraSectionArr removeAllObjects];
    [self.dataArr enumerateObjectsUsingBlock:^(RHVppSetCommonModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [sectionModel.rows enumerateObjectsUsingBlock:^(RHVppSetCommonModel * _Nonnull rowModel, NSUInteger idx, BOOL * _Nonnull stop) {
            //系统设置不提交(单独提交)
            if ([rowModel.type isEqualToString:@"date"]) {
                return;
            }
            //工作模式 充电使能
            if ([rowModel.type isEqualToString:@"switch"]||[rowModel.type isEqualToString:@"select"]) {
                NSString *value = rowModel.content;
                if (rowModel.content.length == 0) {
                    value = @"0";
                }
                NSMutableDictionary *textDic = [NSMutableDictionary dictionary];
                [textDic setObject:rowModel.format forKey:@"dataType"];
                [textDic setObject:rowModel.key forKey:@"paramName"];
                [textDic setObject:value forKey:@"value"];
                [textDic setObject:@(rowModel.regAddr) forKey:@"regAddr"];
                [textDic setObject:@(rowModel.num) forKey:@"num"];
                [textDic setObject:@(rowModel.offset) forKey:@"offset"];
                [self.paraSectionArr addObject:textDic];
            }
            
            //时间段设置
            if ([rowModel.type isEqualToString:@"time"]) {
               
                [rowModel.items enumerateObjectsUsingBlock:^(RHVppSetCommonModel * _Nonnull itemModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    NSString *value = itemModel.content;
                    if (itemModel.content.length == 0) {
                        value = @"0";
                    }
                    NSMutableDictionary *itemDic = [NSMutableDictionary dictionary];
                    [itemDic setObject:itemModel.format forKey:@"dataType"];
                    [itemDic setObject:itemModel.key forKey:@"paramName"];
                    [itemDic setObject:value forKey:@"value"];
                    [itemDic setObject:@(itemModel.regAddr) forKey:@"regAddr"];
                    [itemDic setObject:@(itemModel.num) forKey:@"num"];
                    [itemDic setObject:@(itemModel.offset) forKey:@"offset"];
                    
                    //时间
                    if ([itemModel.type isEqualToString:@"date"]) {
                        NSString *content = [itemModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                        [itemDic setObject:ValidNullData(content) forKey:@"value"];
                    }
                    
                    
                    [self.paraSectionArr addObject:itemDic];
                }];
              
                
            }
            
        }];
       
        
    }];
    
   
}


#pragma mark ------ 参数设置 提交参数
- (void)devParamsSetFromNetwork{
    
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    
    //分组id
    [requestPara setObject:@(self.groupModel.groupId) forKey:@"groupId"];
    if (self.userGroupModel) {
        [requestPara setObject:@(self.userGroupModel.groupId) forKey:@"groupId"];
    }
    
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    
  
   //一次性发送

    //全部参数一次性给到后台 , 不需要填端点sn参数,因为获取不到
    [paraListArr addObjectsFromArray:self.paraSectionArr];
    if (paraListArr.count == 0) {
        return;
    }
    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:15];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDictionary *headContent = @{
        @"cmdId": randomStr,
        
        @"paramCount":@(paraListArr.count),
       
        @"messageType": @(1),//下行
        @"namespace": @"ParamSetSingle",
        @"payloadVersion": @(1),
        @"timestamp": @((NSInteger)interval)
      };
    [requestPara setValue:headContent forKey:@"protocolHead"];
    NSString *url = H_groupVppSet;
    if (self.userGroupModel) {
        url = H_userGroupVppSet;
    }
    [QMUITips showLoading:@"设置中...".rh_localized inView:kAppWindow];
    [BaseModel startWithCompletionAPIKey:url argument:requestPara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        if (resultModel.code == 200) {

            [QMUITips showSucceed:@"设置完成".rh_localized inView:self.view hideAfterDelay:1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (self.finishBlock) {
                    self.finishBlock();
                }
            });
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {

    }];
}



-(UIView*)footerView{
    kWeakSelf;
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 80)];
    
    QMUIButton *commitBtn = [[QMUIButton alloc]init];
    [commitBtn setTitle:@"提交".rh_localized forState:UIControlStateNormal];
    [commitBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [commitBtn setCornerRadius:8];
    [commitBtn setBackgroundColor:CMainColorGreen];
    [footer addSubview:commitBtn];
    [commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.offset(45);
        make.centerY.mas_offset(0);
    }];
    
  
    
    [[commitBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf checkParaEnableStatus];
    }];
    
  
    return footer;
}


-(void)cancelWork:(UIButton*)button
{
    [[NetworkAgent sharedAgent] cancelAllRequests];
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
   
   
}
@end
